/**
 * Created by obesitychow on 8/20/23
 */

package ai.tuobot.sdk.network

import ai.tuobot.app.BuildConfig
import android.util.Log
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

class ApiExt(baseApiUrl: String = BuildConfig.API_BASE_URL){
    val trustAllCertificates: TrustManager = object : X509TrustManager {
        override fun checkClientTrusted(chain: Array<out java.security.cert.X509Certificate>?, authType: String?) {
            // 不做任何操作，信任所有客户端证书
        }

        override fun checkServerTrusted(chain: Array<out java.security.cert.X509Certificate>?, authType: String?) {
            // 不做任何操作，信任所有服务器端证书
        }

        override fun getAcceptedIssuers(): Array<java.security.cert.X509Certificate> {
            return emptyArray() // 返回空数组表示信任所有颁发机构
        }
    }

    fun initSSLContext(): SSLContext {
        val sslContext = SSLContext.getInstance("TLS")
        sslContext.init(null, arrayOf(trustAllCertificates), java.security.SecureRandom())
        return sslContext
    }

    private val okHttpClient = OkHttpClient.Builder()
        .addInterceptor(RetrofitExceptionInterceptor()) // 添加异常处理拦截器
        // 添加其他配置...
        .hostnameVerifier { _, _ -> true } // 忽略主机名验证
        .sslSocketFactory(initSSLContext().socketFactory, trustAllCertificates as X509TrustManager)
        .build()

    private val retrofit = Retrofit.Builder()
        .baseUrl(baseApiUrl)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build()

    fun <T> api(definingClass: Class<T>): T {
        return retrofit.create(definingClass)
    }

    private class RetrofitExceptionInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val request = chain.request()
            val response: Response

            try {
                response = chain.proceed(request)
            } catch (e: Exception) {
                Log.e("Network", "on err", e)
                return Response.Builder()
                    .request(request)
                    .protocol(Protocol.HTTP_1_1)
                    .code(200)
                    .message("OK")
                    .body("[]".toResponseBody("application/json".toMediaTypeOrNull()))
                    .build()
            }

            return response
        }
    }
}


